package com.kzj.xfxh.webSocket;

import com.alibaba.fastjson.JSONObject;
import com.kzj.common.constant.GlobalConstant;
import com.kzj.common.re.Result;
import com.kzj.common.util.AuthUrlUtil;
import com.kzj.xfxh.api.XfxhApiPlusBySocket;
import com.kzj.xfxh.entity.RoleContent;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@ServerEndpoint("/ws/{id}")
@Component
@Slf4j
public class XfxhWebSocketServer {
//    @Autowired
    static AuthUrlUtil authUrlUtil;
    @Autowired
    public void setAuthUrlUtil(AuthUrlUtil authUrlUtil)
    {
        XfxhWebSocketServer.authUrlUtil=authUrlUtil;
    }
    private boolean lock=true;
    private static Map<String,List<RoleContent>> historyList=new HashMap<>();// 对话历史存储集合
    private static Map<String, Session> pools=new HashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id)
    {
        pools.put(id,session);
        historyList.put(id,new ArrayList<>());
        log.info("id: "+id+" 连接成功");
    }
    @OnMessage
    public void onMessage(String msg,@PathParam("id") String id)
    {
        log.info("收到来自id: "+id+" 的消息:"+msg);
        if(tryLock())
        {
            ask(id,msg);
            unLock();
        }
        else{
            try {
                sendMessageToId(id, Result.error(GlobalConstant.WAIT_A_MOMENT));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    @OnClose
    public void onClose(@PathParam("id") String id)
    {
        pools.remove(id);
    }
    public static void sendMessageToId(String id,Result result) throws IOException {
        Session session = pools.get(id);
        session.getBasicRemote().sendText(JSONObject.toJSONString(result));
    }
//    @MyAopLogRunTime
    public   void  ask(String id,String question)
    {
        System.out.println(authUrlUtil);
        System.out.println(authUrlUtil.getXfxhProperties());
        // 构建鉴权url
        String authUrl = null;
        try {
            authUrl = authUrlUtil.getAuthUrl();
        } catch (Exception e) {
            throw new  RuntimeException(e);
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        client.newWebSocket(request,new XfxhApiPlusBySocket(authUrlUtil.getXfxhProperties(), id, question,historyList.get(id), new Consumer<Result>() {
            @Override
            public void accept(Result result) {
                try {
                    sendMessageToId(id,result);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }) );
    }
    public boolean tryLock()
    {
        if(lock)
        {
            lock=false;
            return true;
        }
        return false;
    }
    public void unLock()
    {
        lock=true;
    }


}
